
import os
import json
from flask import Flask, Response, render_template
from flask import request
from werkzeug.utils import secure_filename
from flask import jsonify
import paddlehub as hub

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

basedir = os.path.abspath(os.path.dirname(__file__))

"""
图片上传服务器
"""
@app.route('/upload',methods=['GET','POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        filename = secure_filename(f.filename)

        #f.save(os.path.join('app/static',filename))
        if os.path.isdir('static/photo/'):
            f.save('static/photo/'+str(filename))
        else:
            os.makedirs('static/photo/')
            f.save('static/photo/'+str(filename))

        imgNamePath=basedir+'/static/photo/'+str(filename)

        reqData = request.form.get("data")
        OcrType = json.loads(reqData)["detType"]
        isFc = json.loads(reqData)["fc"]

        if isFc == "y":
            res = ocr( OcrType, imgNamePath ).id_cord()
            res = ocrFormat( res ).fc()
        elif isFc == "n":
            res = ocr( OcrType, imgNamePath ).id_cord()

        return jsonify(res)
    else:
        return render_template('index.html')

class ocr:
    def __init__(self, OcrType, imgNamePath):
        self.OcrType = OcrType # cpu/gpu
        self.imgNamePath = imgNamePath # 识别图片保存路径

    def id_cord(self):
        """
        识别身份证并返回结果
        """
        det_model_dir = "inference/ch_ppocr_server_v2.0_det_infer/"
        rec_model_dir = "inference/ch_ppocr_server_v2.0_rec_infer/"
        result = []

        cmd = "python3 tools/infer/predict_system.py \
                --det_model_dir="+det_model_dir+" \
                --rec_model_dir="+ rec_model_dir+"\
                --use_gpu=" + self.OcrType + " \
                --image_dir="+ self.imgNamePath
        try:
            resultList = os.popen(cmd).readlines()
            for i in range(3,len(resultList)-1):
                result.append(resultList[i].replace('\n', ''))
        except Exception as e:
            result.append(e)

        return result

class ocrFormat:
    def __init__(self, raw_data):
        self.raw_data = raw_data
    def fc(self):
        list_raw = []
        word = ''
        word = word.join(self.raw_data)
        list_raw.append([word])

        lac = hub.Module(name="lac")
        for texts in list_raw: # 每一次取一个列表中的 元素，这个 元素 是个 字符串 的 列表
            results = lac.lexical_analysis(texts=texts, use_gpu=False, batch_size=1, return_tag=1 )
        return results[0]['word']

if __name__ == '__main__':
    app.run(host='0.0.0.0')
    # app.run(host='0.0.0.0', port='8080')